"use strict";

/**
 * 服务器列表控制器
 */
angular.module("app").controller("configListCtrl", function($scope, $http, $route, $location, FileUploader) {

	$scope.serverId = $route.current.pathParams.serverId;
	$scope.server = {
        data : {
        	rootdir : "",
        	id : ""
        },
        init : function(){
        	$http.get("/server/get?sid=" + $scope.serverId,{
        		cache	:	true
        	}).success(function(d) {
        		if(d.success){
        			$scope.server.data = d.ret.server;
        		}
        	});
        }
    };
	$scope.server.init();
	
	$scope.configList = {
		datas	:	[],
		find	:	function(id){
			for(var i = 0; i < this.datas.length; i++){
				var config = this.datas[i];
				if(config.id == id){
					return i;
				}
			}
			return -1;
		},
		getBranch :  function(id){
			var branchConfigs = [];
			var configIdx = this.find(id);
			var branchParent = this.datas[configIdx];
			for(var i= configIdx; i < this.datas.length; i++){
				var config = this.datas[i];
				if(i == configIdx){
					branchConfigs.push(config);
				} else if(config.level <= branchParent.level){
					break;
				} else {
					branchConfigs.push(config);
				}
			}
			return branchConfigs;
		},
		getSelected :  function(){
			for(var i= 0; i < this.datas.length; i++){
				var config = this.datas[i];
				if (config.selected){
					 return config;
				}
			}
			return null;
		},
        remove :  function(id){
            var targetIdx = this.find(id);
            var config = this.datas[targetIdx];
            if(targetIdx > -1){
                //先关闭展示子节点
                if (config.state != "NONE") {
                    $scope.treeNodeCollapse(id);
                }
                this.datas.splice(targetIdx, 1);
            }
        },
        loadData : function(index, config){
        	var url = "/config/list/?sid=" + $scope.serverId;
        	if(config != null){
        		url += "&path=" + config.absolutePath + "&plevel=" + config.level;
        	}
        	$http.get(url).success(function(d) {
        		if(d.success){
        			if(config){
        				if(d.ret.configList != null && d.ret.configList.length > 0){
            				var head = $scope.configList.datas.slice(0, index + 1);
            				var tail = $scope.configList.datas.slice(index + 1, $scope.configList.datas.length);
            				$scope.configList.datas = head.concat(d.ret.configList,tail);
            				$.each(d.ret.configList, function(index, bconfig){
            					bconfig.visible = true;
            				});
        				} else {
        					config.state = "NONE";
        				}
        				config.initialized = true;
        			}else{
        				$scope.configList.datas = d.ret.configList;
        			}
        		}
        	});
        },
        init : function(){
        	this.loadData();
        }
	};
	//初始化配置树
	$scope.configList.init();
	
	$scope.treeNodeClick = function(id){
		$.each($scope.configList.datas, function(index, config){
			if (config.id == id){
				config.selected = true;
			} else {
				config.selected = false
			}
		});
	}
	
	$scope.treeNodeCollapse = function(id){			
		var branchConfigs = $scope.configList.getBranch(id);
		$.each(branchConfigs, function(index, bconfig){
			if(bconfig.id != id){
				bconfig.visible = false;			
			}
			if(bconfig.state == "OPEN"){
				bconfig.state = "CLOSE";
			}
		});
	}
	
	$scope.treeNodeExpand = function(id){
		var configIdx = $scope.configList.find(id);
		var config = $scope.configList.datas[configIdx];
		if(config.state == "CLOSE"){
			config.state = "OPEN";
		}
		
		var branchConfigs = $scope.configList.getBranch(id);
		$.each(branchConfigs, function(index, bconfig){
			if(bconfig.level == config.level + 1){
				bconfig.visible = true;
			}
		});
		
		if(!config.initialized){
			$scope.configList.loadData(configIdx, config);
		}
	}
	
	/**
	 * 配置添加模型
	 */
	$scope.configAddModel = {
		data : null,
		init : function(){
			this.data = {
                serverId        :   $scope.server.data.id,
				configPath		:	$scope.server.data.rootdir,
				configName		:	"",
				isDir			:	false,
				description		:	""
			}
		},
		openDialog : function(serverId){
			$scope.configAddModel.init();
			var selectedConfig = $scope.configList.getSelected();
			if(selectedConfig){
				$scope.configAddModel.data.configPath = selectedConfig.absolutePath;
			}
			//$scope.configAddModel.attach(serverId);
			$("#config_add_modal").modal("show");
		}
	}

    var uploader = $scope.uploader = new FileUploader({
        url: '/config/addFile',
        removeAfterUpload: true
    })

    uploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            return this.queue.length < 10;
        }
    });

    uploader.onBeforeUploadItem = function(item) {
        item.formData.push($scope.configAddModel.data);
    };

    uploader.onCompleteAll = function() {
        if(this.queue.length == 0) {
            $("#config_add_modal").modal('hide');
            location.reload();
        }
    };

    $scope.uploadAll = function() {
        uploader.uploadAll();
    }
	
	$scope.viewConfig = function(id){
		var configIdx = $scope.configList.find(id);
		var config = $scope.configList.datas[configIdx];
		
		var url = "/config/view/"+config.serverId + "/" + config.configType + "/" + encodeURIComponent(config.absolutePath);
		$location.path(url);
	}
	
	$scope.editConfig = function(id){
		var configIdx = $scope.configList.find(id);
		var config = $scope.configList.datas[configIdx];
		
		var url = "/config/edit/"+config.serverId + "/" + config.configType + "/" + encodeURIComponent(config.absolutePath);
		$location.path(url);
	}

    $scope.deleteConfig = function(id){
        var configIdx = $scope.configList.find(id);
        var config = $scope.configList.datas[configIdx];
        var delMessage = "确认删除吗？";
        if(config.isDir) {
            delMessage = "将删除目录下所有文件，确认删除吗？";
        }
        $.confirm({
            title: false,
            content: delMessage,
            confirm: function(){
                $http.post("/config/ddel", config).success(function(d) {
                    if(d.success){
                        $scope.configList.remove(id);
                    }
                });
            }
        });
    }
    
    $scope.mkDir = function() {
        $http.post("/config/addDir", $scope.configAddModel.data).success(function(d) {
            $("#config_add_modal").modal('hide');
            $.alert({
                title: false,
                content: d.message,
                confirm: function() {
                    if(d.success) {
                        location.reload();
                    }
                }
            });
        });
    }

});
